import functools
import datetime
from utils.jwttoken import myjwt

from flask import Blueprint,request,jsonify
from db import db1
from utils.acl import acl
from utils.user_role import user_role
from utils.rbac import rbac
from utils.redisconn import r


bp_resource = Blueprint('resource',__name__)


def getPor(fun):
    @functools.wraps(fun)
    def wrapper(*args,**kargs):
        # 获取token
        token = request.headers['Token']
        # 解析token
        payload = myjwt.jwt_de(token)
        uid = payload['data']['uid']
        # 根据uid查询职务编号
        sql = "select dutys.coding as coding from dutys left join users on dutys.id=users.dutys_id where users.id=%d" %int(uid)
        res = db1.find(sql)
        if res['coding'] == '003':
        # 获取当前ip地址
            ip = request.remote_addr
            # 获取当前日期
            time = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d')
            values = r.get_all_hash_params('abac')
            for k,v in values.items():
                value = str(v,encoding='utf8')
                key = str(k,encoding='utf8')
                if key == 'ip':
                    if value != ip:
                        return jsonify({'code':401,'msg':'ip无权限'})
                if key == 'time':
                    timev = eval(r.get_hash_params('abac','time'))
                    if time<timev[0] or time>timev[1]:
                        return jsonify({'code':4001,'msg':'无时间权限'})
        #     读取限制
            if request.method != "GET":
                return jsonify({'code':4010,'msg':'无法读取'})

        return fun(*args,**kargs)
    return wrapper




@bp_resource.route('/resourcelist',methods=['POST','GET'])
def resourcelist():
    if request.method == 'GET':
        data = acl.get_pagedelist()
        return jsonify({'code':200,'list':data})
    else:
        res = request.json
        data = acl.update_resource(res['userid'],res['reslist'])
        return jsonify({'code':200})


@bp_resource.route('/user_res')
def user_res():
    user_id = request.args.get('user_id')
    sql = "select resource_id from user_res where user_id=%d"%int(user_id)
    res = db1.find_all(sql)
    list1 = []
    for i in res:
        list1.append(i['resource_id'])
    return jsonify({'code':200,'list':list1})



@bp_resource.route('/config_user_role',methods=['POST','GET'])
def config_user_role():
    data = request.json
    user_role.update_user_role(data['user_id'],data['urlist'])
    return jsonify({'code':200})


@bp_resource.route('/rolelist',methods=['POST','GET'])
def rolelist():
    sql = "select * from role "
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})

@bp_resource.route('/role_res',methods=['POST','GET'])
def role_res():
    data = request.json
    rbac.update_role_resource(data['role_id'],data['reslist'])
    return jsonify({'code':200})



@bp_resource.route('/index')
def index():
    user_id = request.args.get('user_id')
    sql = "select * from resource where pid=0"
    res = db1.find_all(sql)
    if user_id:
        for i in res:
            sql = "select resource.id,resource.name,resource.url from  user_res inner join " \
                  "resource on user_res.resource_id=resource.id where user_res.user_id=%d and resource.type=1 and resource.pid=%d"% (int(user_id),int(i['id']))
            i['son'] = db1.find_all(sql)

        return jsonify({'code': 200, 'list': res})
    else:
        for i in res:
            sql1 = "select * from resource where pid=%d"%int(i['id'])
            i['son'] = db1.find_all(sql1)

        return jsonify({'code':200,'list':res})


